package errcode

var msgMap = map[int]string{}

func registerMap(m map[int]string) {
	for code, msg := range m {
		if _, ok := msgMap[code]; ok {
			panic("repeat declare error code")
		}

		msgMap[code] = msg
	}
}

type Response struct {
	code int
	msg  string
	data interface{}
}

// Data ...
func (r *Response) Data() interface{} {
	return r.data
}

// Msg ...
func (r *Response) Msg() string {
	return r.msg
}

// Code ...
func (r *Response) Code() int {
	return r.code
}

// Error ...
func (r *Response) Error() string {
	return r.Msg()
}

// Trigger ...
func Trigger(code int, opts ...interface{}) error {
	var data interface{}
	if len(opts) > 0 {
		data = opts[0]
	} else {
		data = struct{}{}
	}

	if msg, ok := msgMap[code]; !ok {
		panic("use undefined error code")
	} else {
		return &Response{
			code: code,
			msg:  msg,
			data: data,
		}
	}
}

//AuthFailure
func AuthFailure() error {
	return &Response{
		code: 403,
		msg:  "AppId与AppSecret校验失败",
	}
}

//InvalidParam
func InvalidParam(msg string) error {
	return &Response{
		code: 400,
		msg:  msg,
	}
}
